package com.jswty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

import java.nio.ByteOrder;

import static io.netty.util.CharsetUtil.UTF_8;

/**
 * zabbix 被动模式
 *
 * @author senowang
 * @date 2018/10/15 - 15:33
 */
public class ZabbixPassiveServer {
    static final int PORT = Integer.parseInt(System.getProperty("port", "10055"));
    
    public static void main(String[] args) throws Exception {
        EventLoopGroup boss = new NioEventLoopGroup(1);
        EventLoopGroup woker = new NioEventLoopGroup();
        
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boss, woker).channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 100)
                    .handler(new LoggingHandler(LogLevel.DEBUG))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline p = ch.pipeline();
                    //100M
                    p.addLast(new LengthFieldBasedFrameDecoder(
                            //小端模式
                            ByteOrder.LITTLE_ENDIAN,
                            //消息允许最大长度
                            104857600,
                            //消息长度在消息体里面的偏移量
                            5,
                            //消息长度字段占用长度
                            8,
                            //
                            0,
                            //跳过不是消息部分的长度（整个消息体去掉消息头的协议和消息长度）
                            13,
                            true));
                    p.addLast(new StringDecoder(UTF_8));
                    p.addLast(new ZabbixAgentPassiveHandler());
                }
            });
            // Start the client.
            ChannelFuture f = serverBootstrap.bind(PORT).sync();
            // Wait until the connection is closed.
            f.channel().closeFuture().sync();
        } finally {
            // Shut down the event loop to terminate all threads.
            boss.shutdownGracefully();
            woker.shutdownGracefully();
        }
    }
}
